<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>AI 聊天界面</title>
  <style>
    body {
      font-family: Arial, sans-serif;
    }
    #chat-container {
      border: 1px solid #ccc;
      height: 400px;
      overflow-y: scroll;
      margin-bottom: 10px;
      padding: 10px;
    }
    #user-input {
      width: 80%;
      padding: 5px;
      margin-right: 5px;
    }
    #send-button {
      width: 15%;
      padding: 5px;
    }
  </style>
</head>
<body>
<div id="chat-container"></div>
<input type="text" id="user-input" placeholder="请输入您的问题">
<button id="send-button">发送</button>

<script>
  const chatContainer = document.getElementById('chat-container');
  const userInput = document.getElementById('user-input');
  const sendButton = document.getElementById('send-button');

  sendButton.addEventListener('click', function() {
    const inputText = userInput.value;
    if (inputText.trim()!== '') {
      displayMessage('傻蛋', inputText);
      sendRequest(inputText);
      userInput.value = '';
    }
  });

  function displayMessage(sender, message) {
    const messageElement = document.createElement('p');
    messageElement.textContent = `${sender}: ${message}`;
    chatContainer.appendChild(messageElement);
    chatContainer.scrollTop = chatContainer.scrollHeight;
  }

  function sendRequest(inputText) {
    fetch('https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-3.5-8k-0613?access_token=24.bae478ebce5e7a573aba897d1542d914.2592000.1738219245.282335-116898821', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        "messages": [
          {
            "role": "user",
            "content": inputText
          }
        ],
        "enable_system_memory": false,
        "disable_search": false,
        "enable_citation": false,
        "enable_trace": false
      })
    })
            .then(response => response.text())
            .then(data => {
              const jsonData = JSON.parse(data);
              if (jsonData.result) {
                displayMessage('AI', jsonData.result);
              } else {
                displayMessage('AI', 'AI没有返回有效响应，请检查输入或稍后重试。');
              }
            })
            .catch(error => {
              displayMessage('AI', '请求过程中发生错误：' + error.message);
            });
  }
</script>
</body>
</html>